package blobQuickstart.blobAzureApp.controller;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.http.entity.StringEntity;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;




import com.dearbinge.utils.Constants;
//import blobQuickstart.blobAzureApp.service.AzureService;
import com.dearbinge.utils.ResultMsg;
import com.dearbinge.utils.httpClient.ApiRequest;
import com.dearbinge.utils.httpClient.ApiResponse;
import com.google.common.net.MediaType;
import com.microsoft.azure.storage.CloudStorageAccount;
import com.microsoft.azure.storage.OperationContext;
import com.microsoft.azure.storage.blob.BlobContainerPublicAccessType;
import com.microsoft.azure.storage.blob.BlobRequestOptions;
import com.microsoft.azure.storage.blob.CloudBlobClient;
import com.microsoft.azure.storage.blob.CloudBlobContainer;
import com.microsoft.azure.storage.blob.CloudBlockBlob;

@CrossOrigin
@SuppressWarnings("all")
@RestController
@RequestMapping("/azure")
@EnableAutoConfiguration
public class AzureController extends WebMvcConfigurerAdapter {


//	@Autowired
//	private AzureService azureService;


//	@Autowired
//	 private RedisService redisService;



	public static final String storageConnectionString =
			"DefaultEndpointsProtocol=https;" +
			"AccountName=uwz;" +
			"AccountKey=wkbPwCNUYtz6AtkjQpNFH8T9p04b84SNT9r7aDHMea8EM9m5iXBP+HM3DtPvI3xIMlHP7MBWeM+tKNKPrPMCMA==;EndpointSuffix=core.chinacloudapi.cn";



	/**
	 * 单个上传
	 * @param request
	 * @return
	 */
//	@NoRepeatSubmit
	@RequestMapping(value="/upload",method=RequestMethod.POST)
	public ResultMsg<String> upload(@RequestPart("file") MultipartFile file){
		CloudBlobClient blobClient = null;
		CloudBlobContainer container=null;
		CloudStorageAccount storageAccount;
		CloudBlockBlob blob;
		URI primaryUri;
		try {
			//CloudStorageAccount 类表示一个 Azure storage account，我们需要先创建它的实例，才能访问属于它的资源。
			storageAccount = CloudStorageAccount.parse(storageConnectionString);
			//CloudTableClient 类是 Windows Azure Table Service 客户端的逻辑表示，我们需要使用它来配置和执行对 Table storage 的操作。
			blobClient = storageAccount.createCloudBlobClient();
			//我们需要创建一个实例去引用 Table storage 中的一张表，测试用的表名叫”quickstartcontainer”。
			container = blobClient.getContainerReference("quickstartcontainer");
			// 如果不确定表是否被创建过，可以调用CreateIfNotExists方法。
			container.createIfNotExists(BlobContainerPublicAccessType.CONTAINER, new BlobRequestOptions(), new OperationContext());

			String fileName = file.getOriginalFilename();
			blob = container.getBlockBlobReference(fileName);
			blob.upload(file.getInputStream(), 1048576*10);


			//查询全部
//			for (ListBlobItem blobItem : container.listBlobs()) {
//				System.out.println("URI of blob is: " + blobItem.getUri());
//		    }
			//查询单个
			blob = container.getBlockBlobReference(fileName);
			primaryUri = blob.getStorageUri().getPrimaryUri();
//			System.out.println("primaryUri===="+primaryUri);


			//校验图片的合法性
			String a = "{\"DataRepresentation\":\"URL\",\"Value\":\""+primaryUri.toString()+"\"}";
			 StringEntity s = new StringEntity(a);
			Map map = new HashMap<String, String>();
			map.put("Content-Type","application/json");
			map.put("Ocp-Apim-Subscription-Key",Constants.OCP_APIM_SUBSCRIPTION_KEY_CS);
			ApiResponse api = new ApiRequest("https://chinaeast2.api.cognitive.azure.cn/contentmoderator/moderate/v1.0/ProcessImage/Evaluate?CacheImage=true",ApiRequest.Verb.POST)
			.setHeaders(map)
			.setEntity(s)
			.charset("UTF-8")
			.send();
			String result = new String(api.getContent(), "UTF-8");
			JSONObject json = JSONObject.fromObject(result);
			if(!json.get("IsImageRacyClassified").toString().equals("false")){
				return ResultMsg.error(501, "非法图片请重新上传!");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ResultMsg.error(500, "error");
		}
		return ResultMsg.ok(primaryUri.toString());
	}


	/**
	 * 上传视频
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/uploadVideo",method=RequestMethod.POST)
	public ResultMsg<String> uploadVideo(@RequestPart("file") MultipartFile file){
		CloudBlobClient blobClient = null;
		CloudBlobContainer container=null;
		CloudStorageAccount storageAccount;
		CloudBlockBlob blob;
		URI primaryUri;
		try {
			//CloudStorageAccount 类表示一个 Azure storage account，我们需要先创建它的实例，才能访问属于它的资源。
			storageAccount = CloudStorageAccount.parse(storageConnectionString);
			//CloudTableClient 类是 Windows Azure Table Service 客户端的逻辑表示，我们需要使用它来配置和执行对 Table storage 的操作。
			blobClient = storageAccount.createCloudBlobClient();
			//我们需要创建一个实例去引用 Table storage 中的一张表，测试用的表名叫”quickstartcontainer”。
			container = blobClient.getContainerReference("quickuploadvideo");
			// 如果不确定表是否被创建过，可以调用CreateIfNotExists方法。
			container.createIfNotExists(BlobContainerPublicAccessType.CONTAINER, new BlobRequestOptions(), new OperationContext());
			String fileName = file.getOriginalFilename();
			blob = container.getBlockBlobReference(fileName);
			blob.upload(file.getInputStream(), 1048576);
			//查询单个
			blob = container.getBlockBlobReference(fileName);
			primaryUri = blob.getStorageUri().getPrimaryUri();
		} catch (Exception e) {
			e.printStackTrace();
			return ResultMsg.error(500, "error");
		}
		return ResultMsg.ok(primaryUri.toString());
	}

	/**
	 * 删除Blob
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/deleteBlob",method=RequestMethod.GET)
	public Boolean deleteBlob(){
		CloudBlobClient blobClient = null;
		CloudBlobContainer container=null;
		CloudStorageAccount storageAccount;
		CloudBlockBlob blob;
		try {
             //建立连接
            storageAccount = CloudStorageAccount.parse(storageConnectionString);
            blobClient = storageAccount.createCloudBlobClient();
            container = blobClient.getContainerReference("quickstartcontainer");
            blob = container.getBlockBlobReference("2010.jpg");
            //删除blob
            blob.delete();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}



}
